package com.zgh.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * 读取/下载、上传文件
 */
public class GetFileUtil {

    private static final Logger LOGGGER = LoggerFactory.getLogger(GetFileUtil.class);
    /**
     * 下载文件
     * @param response
     * @param path
     * @param fileName
     * @throws IOException
     */
    public static void loadExcel(HttpServletResponse response, String path, String fileName) {
        //获取输入流，模板位置:根路径下使用相对路径获取
        try {
            InputStream bis = new BufferedInputStream(new FileInputStream(new File(path)));
            //转码，免得文件名中文乱码
            fileName = URLEncoder.encode(fileName,"UTF-8");
            //设置文件下载头
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
            response.setContentType("multipart/form-data");
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            int len = 0;
            while((len = bis.read()) != -1){
                out.write(len);
                out.flush();
            }
            out.close();
            bis.close();
        } catch (IOException e) {
            LOGGGER.error("文件下载失败:", e);
            e.printStackTrace();
        }
    }


    /**
     * 判断文件下的是否存在某个文件
     * @param path 文件夹地址
     * @param fileName 文件名称
     * @return
     */
    public static Boolean  getFile(String path,String fileName) {
        File file = new File(path);
        File[] files = file.listFiles();
        if (files!=null&&files.length>0){
            for (File fil : files) {
                if (fileName.equals(fil.getName())){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取未处理的文件
     * @param path
     * @param fileName
     * @return
     */
    public static File getUnprocessedFile(String path,String fileName){
        File file = new File(path);
        File unprocessedFile=null;
        File[] files = file.listFiles();
        if (files!=null){
            for (File fil : files) {
                if (fil.getName().indexOf(fileName)>-1){
                    unprocessedFile=fil;
                    break;
                }
            }
        }
        return  unprocessedFile;
    }


    /**
     * 上传文件到指定路径
     * @param mFile 要上传的文件
     * @param path  指定路径
     */
    public static void uploadFile(MultipartFile mFile, String path) {
        try {
            InputStream in = mFile.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            File file = new File(path);
            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            OutputStream out = new FileOutputStream(path);
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.close();
            in.close();
        } catch (Exception e) {
            LOGGGER.error("文件上传失败", e);
            e.printStackTrace();
        }
    }

    /**
     * 删除单个文件
     * @param filepath
     * @param name
     */
    public static void deleteDirectory(String filepath,String name){
        File  file= GetFileUtil.getUnprocessedFile(filepath,name);
        File[] list = file.listFiles();
        if ( file.exists() && file.isFile()) {
            file.delete();
        }
        if (!file.delete()) {
            LOGGGER.error("请关闭使用该文件的所有进程或者流！！");
        } else {
            LOGGGER.error(file.getName()+" 成功被删除！");
        }
    }

    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }
    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
